package aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author dell
 * @category 动态代理类
 */
public class HelloProxy implements InvocationHandler {

	private Object target;
	private ConfigBean configBean = null;

	public Object getTarget() {
		return target;
	}

	public void setTarget(Object target) {
		this.target = target;
	}

	public ConfigBean getConfigBean() {
		return configBean;
	}

	public void setConfigBean(ConfigBean configBean) {
		this.configBean = configBean;
	}

	// 绑定代理目标
	public Object bind(Object target) {
		this.target = target;

		Object proxy = Proxy.newProxyInstance(target.getClass()
				.getClassLoader(), target.getClass().getInterfaces(), this);
		return proxy;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		// TODO 代理的逻辑
		ConfigBean configBean = getConfigBean();

		if (!configBean.isFlag()) {

			return method.invoke(target, args);
		}
		configBean.before();
		Object obj = null;
		try {
			if (configBean.isUseAround()) {
				obj = configBean.around();
			} else {
				obj = method.invoke(target, args);

			}

		} catch (Exception ex) {
			configBean.afterThrowing();
		}
		configBean.after();
		return obj;
	}

	public static void main(String[] args) throws InstantiationException,
			IllegalAccessException, ClassNotFoundException {
		HelloProxy helloProxy = new HelloProxy();

		HelloService helloService = (HelloService) helloProxy
				.bind(new HelloServiceImpl());
		ConfigBean config = new ConfigBean();
		config.setFlag(true);
		// config.setUseAround(true);
		helloProxy.setConfigBean(config);
		helloService.sayHello("asda");
	}

}
